<template>
  <div class="create-post">
    <h2>发布新帖子</h2>
    <form @submit.prevent="handleSubmit">
      <!-- 帖子类型 -->
      <div class="form-group">
        <label>帖子类型</label>
        <select v-model="form.postType">
          <option value="NORMAL">普通帖子</option>
          <option value="QUESTION">问答贴</option>
        </select>
      </div>

      <!-- 标签选择（多选按钮风格） -->
      <div class="form-group">
        <label>选择标签</label>
        <div class="tag-buttons">
          <div
            v-for="tag in tagList"
            :key="tag.bit"
            :class="['tag-button', form.selectedTags.includes(tag.bit) ? 'selected' : '']"
            @click="toggleTag(tag.bit)"
          >
            {{ tag.label }}
          </div>
        </div>
        <div v-if="form.selectedTags.length === 0 && submitted" class="error-message">
          至少选择一个标签
        </div>
      </div>


      <!-- 标题 -->
      <div class="form-group">
        <label>标题</label>
        <input type="text" v-model="form.title" required placeholder="请输入帖子标题" />
        <div v-if="!form.title && submitted" class="error-message">标题不能为空</div>
      </div>

      <!-- 内容 -->
      <div class="form-group">
        <label>内容</label>
        <textarea 
          v-model="form.content" 
          rows="10" 
          required 
          placeholder="请输入帖子内容..."
        ></textarea>
        <div v-if="!form.content && submitted" class="error-message">内容不能为空</div>
      </div>

      <!-- 图片预览 -->
      <div class="form-group">
        <label>图片（可选）</label>
        <input type="file" multiple @change="handleFileUpload" />
        <div v-if="form.images.length > 0" class="preview-images">
          <img v-for="(image, index) in form.images" :key="index" :src="image" alt="预览图片" class="preview-image" />
        </div>
      </div>
      <!-- 视频上传 -->
      <div class="form-group">
        <label>视频（可选）</label>
        <input type="file" accept="video/*" @change="handleVideoUpload" />
        <div v-if="form.videoPreview" class="preview-video">
          <video controls width="300" :src="form.videoPreview"></video>
        </div>
      </div>


      <!-- 操作按钮 -->
      <div class="form-actions">
        <button type="submit">发布</button>
        <button type="button" @click="$router.back()">取消</button>
      </div>
    </form>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useUiStore } from '@/stores/ui'
import { storeToRefs } from 'pinia'
import { postTypeMap, combinePostTags } from '@/utils/postTypes'
import axios from 'axios'

// 表单数据
const form = ref({
  title: '',
  content: '',
  postType: 'NORMAL', // NORMAL or QUESTION
  selectedTags: [] as number[],
  images: [] as string[],       // 图片预览
  videoPreview: ''              // ✅ 视频预览（临时用）
})


const router = useRouter()
const userStore = useUserStore()
const uiStore = useUiStore()
const { user } = storeToRefs(userStore)
const submitted = ref(false)


const toggleTag = (bit: number) => {
  const idx = form.value.selectedTags.indexOf(bit)
  if (idx === -1) {
    form.value.selectedTags.push(bit)
  } else {
    form.value.selectedTags.splice(idx, 1)
  }
}

// 图片预览处理（实际上传接口另行处理）
const handleFileUpload = (event: Event) => {
  const files = (event.target as HTMLInputElement).files
  if (files) {
    form.value.images = Array.from(files).map(file => URL.createObjectURL(file))
  }
}
const tagList = Object.entries(postTypeMap).map(([bit, label]) => ({
  bit: Number(bit),
  label
}))
form.value.videoPreview = ''

const handleVideoUpload = (event: Event) => {
  const file = (event.target as HTMLInputElement).files?.[0]
  if (file) {
    form.value.videoPreview = URL.createObjectURL(file)
  }
}


// 提交逻辑
const handleSubmit = async () => {
  
  submitted.value = true

  if (!form.value.title || !form.value.content || form.value.selectedTags.length === 0) {
    uiStore.showNotification('请完整填写信息')
    return
  }

  // 用位或合并 selectedTags 数组生成 typeId
  const typeId = combinePostTags(form.value.selectedTags)

  const postData = {
    title: form.value.title,
    content: form.value.content,
    userId: user.value?.userId,
    typeId: typeId,
    postType: form.value.postType
  }

  try {
    const res = await axios.post('/api/knowledge/publish', postData)
    uiStore.showNotification('🎉 发布成功')
    router.push('/home')
  } catch (err) {
    console.error('发布失败', err)
    uiStore.showNotification('发布失败，请稍后再试')
  }
}
</script>

<style scoped>
.create-post {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
  text-align: left;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

input,
textarea,
select {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

textarea {
  resize: vertical;
  min-height: 200px;
}

.error-message {
  color: #F44336;
  font-size: 14px;
  margin-top: 5px;
}

.preview-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.preview-image {
  max-width: 100px;
  max-height: 100px;
  object-fit: cover;
  border-radius: 4px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

button {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button[type="submit"] {
  background-color: #2196F3;
  color: white;
}

button[type="submit"]:hover {
  background-color: #0b7dda;
}

button[type="button"] {
  background-color: #f0f0f0;
  color: #333;
}

button[type="button"]:hover {
  background-color: #e0e0e0;
}

.tag-checkboxes {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.tag-checkboxes label {
  display: flex;
  align-items: center;
  gap: 6px;
  background: #f5f5f5;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
}

.tag-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.tag-button {
  padding: 6px 12px;
  border-radius: 4px;
  background-color: #f5f5f5;
  border: 1px solid #ccc;
  cursor: pointer;
  user-select: none;
  transition: 0.3s;
}

.tag-button:hover {
  background-color: #e0e0e0;
}

.tag-button.selected {
  background-color: #2196F3;
  color: white;
  border-color: #2196F3;
}

.preview-video {
  margin-top: 10px;
}

</style>
